<template>
	<SlotModal ref='slotModalRef' v-bind='slotModalConfig'>
		<n-form ref='formRef' v-bind='formConfig'
				:model='formData' :rules='formRules'>
			<n-grid :x-gap='24' :cols='24'>
				<n-form-item-grid-item span='12' label='公告编码' path='noticeCode'>
					<n-tooltip trigger='click'>
						<template v-slot:trigger>
							<n-input v-model:value='formData.noticeCode' placeholder='请输入公告编码'
									 clearable/>
						</template>
						格式:A001 B001 C001,以顺序字母为开头,以顺序数字为结尾
						<br/>
						栗子:A001B001C002
					</n-tooltip>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='12' label='排序序号' path='sort'>
					<n-input-number v-model:value='formData.sort' placeholder='请输入排序序号'
									style='width:100%;' min='0' clearable/>
				</n-form-item-grid-item>
				<!--<n-form-item-grid-item span='24' :show-feedback='false'>
					<n-divider title-placement='left'>可以看见公告的用户</n-divider>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='8' label='选择部门' path='deptList'>
					<n-switch v-model:value='formData.isLongTime as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='8' label='选择角色' path='roleList'>
					<n-switch v-model:value='formData.isLongTime as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='8' label='选择用户' path='userList'>
					<n-switch v-model:value='formData.isLongTime as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>-->
				<n-form-item-grid-item span='24' :show-feedback='false'>
					<n-divider title-placement='left'>公告展示时长</n-divider>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='12' label='是否长期' path='isLongTime'>
					<n-switch v-model:value='formData.isLongTime as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>
				<n-form-item-grid-item v-if='!formData.isLongTime' span='12' label='展示时长'
									   path='timeRange'>
					<n-date-picker v-model:formatted-value='timeRange' type='datetimerange'
								   format='yyyy-MM-dd HH:mm:ss' value-format='yyyy-MM-dd HH:mm:ss'
								   clearable/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' :show-feedback='false'>
					<n-divider title-placement='left'>其他选项</n-divider>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='12' label='是否热点' path='isHotspot'>
					<n-switch v-model:value='formData.isHotspot as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='12' label='是否启用' path='status'>
					<n-switch v-model:value='formData.status as boolean'
							  :checked-value='true' :unchecked-value='false'>
						<template v-slot:checked>是</template>
						<template v-slot:unchecked>否</template>
					</n-switch>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' :show-feedback='false'>
					<n-divider title-placement='center'>正文区</n-divider>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' label='公告标题' path='title'>
					<n-input v-model:value='formData.title' placeholder='请输入公告标题'
							 clearable/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' label='公告内容' label-placement='top'
									   path='content'>
					<CKEditor-A4 ref='CKEditor5WatchDogRef'
								 v-model:initValue='richTextContent'
								 v-model:htmlValue='formData.content'
								 :editorConfig='editorConfig'/>
				</n-form-item-grid-item>
				<n-form-item-grid-item span='24' :show-feedback='false'>
					<n-flex justify='center' align='center'
							:wrap='false' inline style='width:100%;'>
						<n-button round secondary type='info'
								  @click='submitEvent'>
							提交
						</n-button>
						<n-button round secondary type='default'
								  @click='clearFormData'>
							重置
						</n-button>
					</n-flex>
				</n-form-item-grid-item>
			</n-grid>
		</n-form>
	</SlotModal>
</template>
<script lang='ts' setup>
import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
// axios
import axios from '@/config/axios/index.ts';
// 模态框和打印组件
import { VxeUI } from '@/config/vxe/index.ts';
import type { JsonResultProps } from '#/JsonResult.d.ts';
import { FormInst, FormItemRule, FormProps, FormRules, FormValidationError } from 'naive-ui';
import type { SystemNoticeInfoProps } from '#/src/components/page/systemManager/noticeMaintain/SystemNoticeProps.d.ts';
import { EditorConfig } from '@ckeditor/ckeditor5-core';
const SlotModal = defineAsyncComponent(() => import('@/components/customComponents/modal/SlotModal.vue'));
const CKEditorA4 = defineAsyncComponent(
	() => import('@/components/customComponents/CKEditor5WatchDog/CKEditor-A4.vue'));
// 接收的参数
const props = defineProps({
	reLoad : {
		type    : Function,
		require : true,
		default : null
	}
});
// ----------------------------------------------------------------------
const slotModalConfig = reactive({
	reLoad            : () => props.reLoad(),
	onCloseModalEvent : () => clearFormData(),
	resetEvent        : () => clearFormData()
});
// ----------------------------------------------------------------------
const formConfig = reactive<FormProps>({
	labelWidth           : 'auto',
	labelAlign           : 'left',
	labelPlacement       : 'left',
	size                 : 'large',
	requireMarkPlacement : 'right-hanging'
});
const timeRange = ref<[string, string] | null>(null);
const formData = reactive<Partial<SystemNoticeInfoProps>>({});
const formRules = reactive<FormRules>({
	noticeCode : {
		required : true,
		type     : 'string',
		trigger  : ['input', 'blur'],
		message  : '公告编码是必须的'
	},
	sort       : {
		required : true,
		type     : 'number',
		trigger  : ['input', 'blur'],
		message  : '排序序号是必须的'
	},
	isLongTime : {
		required : true,
		type     : 'boolean',
		trigger  : ['input', 'blur'],
		message  : '是否长期必须选择'
	},
	timeRange  : {
		required : true,
		trigger  : ['input', 'blur'],
		asyncValidator(rule: FormItemRule, value: string, callback: (error?: Error) => void) {
			return new Promise<void>((resolve, reject) => {
				if (!timeRange.value || 2 !== timeRange.value!.length) {
					reject(Error('展示时间必须选择!'));
				}
				resolve();
			});
		}
	},
	isHotspot  : {
		required : true,
		type     : 'boolean',
		trigger  : ['input', 'blur'],
		message  : '请选择是否热点'
	},
	status     : {
		required : true,
		type     : 'boolean',
		trigger  : ['input', 'blur'],
		message  : '请选择是否启用'
	},
	title      : {
		required : true,
		type     : 'string',
		trigger  : ['input', 'blur'],
		message  : '公告标题是必须的'
	},
	content    : {
		required : true,
		type     : 'string',
		trigger  : ['change'],
		message  : '请输入一些公告内容'
	}
});
// ----------------------------------------------------------------------
const editorConfig: EditorConfig = reactive({
	language : 'zh-cn',
	heading  : {
		options : [
			{ model : 'paragraph', title : 'Paragraph', class : 'ck-heading_paragraph' },
			{ model : 'heading1', view : 'h1', title : 'Heading 1', class : 'ck-heading_heading1' },
			{ model : 'heading2', view : 'h2', title : 'Heading 2', class : 'ck-heading_heading2' },
			{ model : 'heading3', view : 'h3', title : 'Heading 3', class : 'ck-heading_heading3' }
		]
	}
});
const richTextContent = ref<string | null>('');
// ----------------------------------------------------------------------
const slotModalRef = ref<InstanceType<typeof SlotModal>>();
const formRef = ref<FormInst>();
const CKEditor5WatchDogRef = ref<InstanceType<typeof CKEditorA4>>();
onMounted(() => {
});
const showModal = async () => {
	await slotModalRef.value!.openModal({
		height     : '500',
		width      : '700',
		title      : '新增公告信息',
		showClose  : true,
		showZoom   : true,
		fullscreen : true
	});
};
const clearFormData = async () => {
	// 清理表单数据
	timeRange.value = null;
	Object.assign(formData, {
		tenantCode : sessionStorage.getItem('loginTenantCode'),
		noticeCode : null,
		sort       : null,
		isLongTime : true,
		startTime  : null,
		endTime    : null,
		isHotspot  : false,
		status     : true,
		title      : null
	});
	// 清理富文本数据
	await CKEditor5WatchDogRef.value?.clearText();
	// 去除表单校验提示
	formRef.value?.restoreValidation();
};
const submitEvent = async () => {
	// 校验菜单
	formRef.value?.validate((errors?: Array<FormValidationError>): void => {
		if (errors) {
			VxeUI.modal.message({ content : '请先完善填写的内容!', status : 'warning', id : 'validateMessage' });
		} else {
			if (formData.isLongTime) {
				formData.startTime = null;
				formData.endTime = null;
			} else {
				formData.startTime = timeRange.value![0];
				formData.endTime = timeRange.value![1];
			}
			// 提交数据
			axios<any, JsonResultProps<any>, any>({
				method : 'POST',
				url    : '/notice/add',
				data   : formData
			}).then((jsonResult: JsonResultProps<any>) => {
				if (jsonResult['status']) {
					// 提示用户
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'success',
						id      : 'successMessage'
					});
					// 刷新数据
					props.reLoad();
					slotModalRef.value!.closeModal();
				} else {
					VxeUI.modal.message({
						content : jsonResult['msg'],
						status  : 'warning',
						id      : 'failedMessage'
					});
				}
			}).catch((error: unknown) => {
				console.error(error);
				VxeUI.modal.message({
					content : '系统异常,请稍后再试',
					status  : 'error',
					id      : 'errorMessage'
				});
			});
		}
	});
};
// 导出方法
defineExpose({ showModal });
</script>